/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.analysis.cli.actions;

import cz.mzk.oai.metadataRepository.analysis.RecordPrintOptions;
import cz.mzk.oai.metadataRepository.metadata.MetadataFormat;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import cz.mzk.oai.metadataRepository.repository.Repository;
import java.io.File;

/**
 *
 * @author Martin
 */
public abstract class AnalyzeElementAction extends Action {

    private static final String LOG_DIR = "analysis_log";
    protected boolean analyzeAllCollections;
    protected MetadataCollection collectionToAnalyze;
    protected final boolean printValues;
    protected final boolean printIdentifiers;
    protected final RecordPrintOptions options;

    public AnalyzeElementAction(Repository repository, String collectionName, boolean printValues, boolean printIdentifiers, RecordPrintOptions options) throws Exception {
        super(repository);
        this.printValues = printValues;
        this.printIdentifiers = printIdentifiers;
        this.options = options;
        determineCollection(collectionName);
    }

    private void determineCollection(String collectionName) throws Exception {
        if (collectionName == null) {
            analyzeAllCollections = true;
            return;
        } else {
            collectionToAnalyze = repository.findCollection(collectionName);
            if (collectionToAnalyze == null) {
                throw new Exception("No such collection " + collectionName);
            }

        }
    }

    protected File buildMetadataDir(MetadataCollection collection, MetadataFormat format) {
        return new File(collection.getRootDir() + File.separator + format.getDirName());
    }

    protected File buildLogFile(MetadataCollection collection, String logName) {
        File logDir = buildLogDir(collection);
        return new File(logDir + File.separator + logName);
    }

    private File buildLogDir(MetadataCollection collection) {
        File logDir = new File(collection.getRootDir() + File.separator + LOG_DIR);
        createDirIfNotExist(logDir);
        return logDir;
    }

    private void createDirIfNotExist(File dir) {
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    public void run() throws Exception {
        if (analyzeAllCollections) {
            for (MetadataCollection col : repository.getCollections()) {
                analyze(col);
                System.out.println("------------------------------------");
            }
        } else {
            analyze(collectionToAnalyze);
        }
    }

    abstract void analyze(MetadataCollection col);
}
